var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');

Page({
  data: {
    orderId: 0,
    orderInfo: {},
    orderGoods: [],
    aftersale: {
      pictures: []
    },
    column: '请选择退款类型',
    columns: ['未收货退款', '不退货退款', '退货退款'],
    hasPicture: false,
    files: []
  },

  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      orderId: options.id
    });
    this.getOrderDetail();
  },
  getOrderDetail: function () {
    wx.showLoading({
      title: '加载中',
    });

    setTimeout(function () {
      wx.hideLoading()
    }, 2000);

    let that = this;
    util.request(api.OrderDetail, {
      orderId: that.data.orderId
    }).then(function (res) {
      if (res.errno === 0) {
        console.log(res.data);
        that.setData({
          orderInfo: res.data.orderInfo,
          orderGoods: res.data.orderGoods,
          'aftersale.orderId': that.data.orderId,
          'aftersale.amount': res.data.orderInfo.actualPrice - res.data.orderInfo.freightPrice
        });
      }
      wx.hideLoading();
    });
  },

  chooseImage: function(e) {
    if (this.data.files.length > 4) {
      util.showErrorToast('只能上传四张图片')
      return false;
    }
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        that.upload(res);
      }
    })
  },
  upload: function(res) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload,
      filePath: res.tempFilePaths[0],
      name: 'file',
      success: function(res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.url
          that.data.aftersale.pictures.push(url)
          that.setData({
            hasPicture: true,
            'aftersale.pictures':that.data.aftersale.pictures
          })
        }
      },
      fail: function(e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  DelImg(e) {
    let that = this;
    wx.showModal({
      title: '图片删除',
      content: '确定要删除这张图片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          that.data.files.splice(e.currentTarget.dataset.index, 1);
          that.data.aftersale.pictures.splice(e.currentTarget.dataset.index, 1)
          that.setData({
            files: that.data.files,
            'aftersale.pictures':that.data.aftersale.pictures
          })
        }
      }
    })
  },
  
  contentInput: function (e) {
    this.setData({
      'aftersale.comment': e.detail,
    });
  },
  onReasonChange: function (e) {
    this.setData({
      'aftersale.reason': e.detail,
    });
  },

  bindMultiPickerChange: function(e) {
    this.setData({
      column: this.data.columns[e.detail.value],
      'aftersale.type': e.detail.value,
    })
  },
  
  submit: function () {
    let that = this;
    if (that.data.aftersale.type == undefined) {
      util.showErrorToast('请选择退款类型');
      return false;
    }

    if (that.data.reason == '') {
      util.showErrorToast('请输入退款原因');
      return false;
    }

    if(that.data.comment){
      util.showErrorToast('请输入退款说明');
      return false;
    }

    if(!that.data.hasPicture){
      util.showErrorToast('请上传凭证');
      return false;
    }

    wx.showLoading({
      title: '提交中...',
      mask: true,
      success: function () {

      }
    });

    util.request(api.AftersaleSubmit, that.data.aftersale, 'POST').then(function (res) {
      wx.hideLoading();
      if (res.errno === 0) {
        wx.showToast({
          title: '申请售后成功',
          icon: 'success',
          duration: 2000,
          complete: function () {
            wx.switchTab({
              url: '/pages/ucenter/index/index'
            });
          }
        });
      } else {
        util.showErrorToast(res.errmsg);
      }

    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})